//
//  KSItemView.swift
//  Supermarket
//
//  Created by liuxm on 2017/9/21.
//  Copyright © 2017年 kushao. All rights reserved.
//

import UIKit

protocol KSItemViewDelegate: NSObjectProtocol {
    func itemClick(tag: Int)
}

class KSItemView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    weak var delegate:KSItemViewDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initView(named: String, description: String, reduce: CGFloat, tag: Int) {
        let image = UIImage.init(named: named)
        let imageWidth = (image?.size.width)!/reduce
        let imageHeight = (image?.size.height)!/reduce
        
        let btnX = (self.frame.size.width - imageWidth)/2
        let btn = UIButton(frame: CGRect(x: btnX, y: 0, width: imageWidth, height: imageHeight))
        btn.setBackgroundImage(UIImage.init(named: named), for: .normal)
        btn.tag = tag
        btn.addTarget(self, action: #selector(itemBtnClick), for: .touchUpInside)
        self.addSubview(btn)
        
        let descriptionLabel = UILabel(frame: CGRect(x: 0, y: self.frame.height - 17, width: self.frame.width, height: 17))
        descriptionLabel.text = description
        descriptionLabel.font = UIFont.systemFont(ofSize: 14)
        descriptionLabel.textColor = KSColor.kColor_3
        descriptionLabel.textAlignment = .center
        self.addSubview(descriptionLabel)
    }
    
    @objc fileprivate func itemBtnClick(sender: UIButton) {
        self.delegate?.itemClick(tag: sender.tag)
    }
}
